<template>
    <a-input v-model:value="FormValue.A"></a-input>
    <a-input v-model:value="FormValue.B"></a-input>

    {{ FormValue }}
</template>
<script setup>
import { ref, watch } from "vue";
import data from "./data.json";

var FormValue = ref({
    A: "",
    B: "",
});

class Form {
    constructor() {}
    SetStatus(key, val) {
        console.log(key, val);
    }
}

var _item = new Form();

// 初始化 Event，减少重复判断事件
for (let i = 0; i < data.length; i++) {
    const element = data[i];
    for (let i = 0; i < element.Events.length; i++) {
        const item = element.Events[i];
        if (item.ValueType == "direct") {
            item.Event = new Function("val", "return " + item.Value);
        } else if (item.ValueType == "function") {
            item.Event = new Function(`return async function(val, FormItem){${item.Value}}`)();
        }
    }
}

// 执行监听事件
for (let i = 0; i < data.length; i++) {
    const element = data[i];
    watch(
        () => FormValue.value[element.key],
        async (val) => {
            for (let i = 0; i < element.Events.length; i++) {
                const item = element.Events[i];
                switch (item.FunKey) {
                    case "Status":
                        _item.SetStatus(item.EventKey, await item.Event(val, _item));
                        break;

                    default:
                        break;
                }
            }
        },
        {
            deep: element.deep,
            immediate: element.immediate,
        }
    );
}
</script>
<style lang="less" scoped></style>
